package com.zareal.ymcc.mq.listener;

import com.alibaba.fastjson.JSON;
import com.zareal.ymcc.domain.CourseOrder;
import com.zareal.ymcc.dto.PayDto;
import com.zareal.ymcc.service.ICourseOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
@RocketMQTransactionListener(txProducerGroup = "tx-course-order-group")
public class RocketMQListen implements RocketMQLocalTransactionListener {
    @Autowired
    private ICourseOrderService courseOrderService;
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        log.info("课程下单本地事务开始执行");
        if (o == null){
            return RocketMQLocalTransactionState.ROLLBACK; // 不消费消息
        }
        CourseOrder courseOrder = JSON.parseObject(o.toString(), CourseOrder.class);
        // 为了防止用户异常操作，多次下单，则加个锁
        synchronized (courseOrder.getOrderNo()){
            // 防止已经存在订单的情况
            // 防止已经保存成功了
            if (courseOrderService.selectByOrderNo(courseOrder.getOrderNo()) != null){
                log.info("课程订单已存在！");
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            courseOrderService.saveCourseOrderAndCourseOrderItems(courseOrder);
        }
        log.info("课程下单执行本地事务结束！");
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        // 1.将数据转换为字节数组
        try {
            byte[] bytes = (byte[]) message.getPayload();
            // 2.转换为我们想要的对象
            String paramStr = new String(bytes, StandardCharsets.UTF_8);
            PayDto payDto = JSON.parseObject(paramStr, PayDto.class);
            if (payDto == null){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            CourseOrder courseOrder = courseOrderService.selectByOrderNo(payDto.getOrderNo());
            if (courseOrder == null){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
